#include "Database.h"

#include <QString>
#include <QFile>
#include <QtSql/QSqlDatabase>
#include <QSqlError>
#include <QDebug>

Database *Database::instance = nullptr;

Database *Database::getInstance() {
    // 用于获取Database的实例，使用单例模式
    if (Database::instance == nullptr) {
        instance = new Database;
    }
    return instance;
}

void Database::connectDatabase(const QString &dbFilename, const QString &connName) {
    // 创建数据库，并且保存到连接中（默认连接名是[library]）
    if (QSqlDatabase::contains(connName)) {
        this->database = QSqlDatabase::database(connName);
    } else {
        this->database = QSqlDatabase::addDatabase("QSQLITE", connName);
    }

    this->database.setDatabaseName(dbFilename);
    this->query = QSqlQuery(this->database);
}

void Database::openDatabase() {
    this->database.open();
}

void Database::closeDatabase() {
    this->database.close();
}

bool Database::isDatabaseOpen() {
    return this->database.isOpen();
}

bool Database::exec(const QString &queryString) {
    if (this->query.exec(queryString)) {
        return true;
    } else {
        qDebug() << this->query.lastError();
        return false;
    }
}

QSqlQuery *Database::getQuery() {
    return &this->query;
}
